package com.example.online_order.interceptor;


import com.auth0.jwt.interfaces.Claim;
import com.example.online_order.Eception.BussinessException;
import com.example.online_order.Eception.ExceptionType;
import com.example.online_order.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer url = request.getRequestURL();
        log.info("url  is  {}",url);
        if(url.toString().contains("login") || url.toString().contains("regist") || url.toString().contains("download")  || url.toString().contains("upload"))
            return true;
        String method = request.getMethod();

        if("options".equalsIgnoreCase(method))
            return true;

        String token = request.getHeader("Authorization");
        System.out.println(token);
        if(token == null || token.equals("")) {
            throw new BussinessException(ExceptionType.bus_invalid_token,"无效token重新登录");
        }else{
            //验证token
            if(!JwtUtils.verifyToken(token))
            {
                throw new BussinessException(ExceptionType.bus_timeout_token,"登录超时重新登录");
            }else{
                log.debug("token 有效");
                //获取用户名
                Claim claimByName = JwtUtils.getClaimByName(token, "userName");
                String name = claimByName.asString();
                log.debug("{}",name);
//                获取用户id
                String sId = JwtUtils.getAudience(token);
                log.debug("{}",sId);
//                放到request对象里
                request.setAttribute("accountId",Integer.parseInt(sId));
                return true;
            }

        }

    }
}
